import React, { useEffect, useState } from 'react';
import { NavBar, Icon, Toast } from "antd-mobile";//引入ui库
import styles from "./style.module.scss";//引入样式
import { connect } from "react-redux";
import axios from '../../utils/request';
import FindRoomItem from "../../components/FindRoomItem";
const { BMap } = window;//把地图实例从window对象解构出来
let map;
let centralPoint = '';//定义地图定位的中心
let zoomDataIndex = 0;
let zoomZIndex = 1;
let zoomData = [
    { id: 1, scale: 11, className: 'map_round' },
    { id: 2, scale: 13, className: 'map_round' },
    { id: 3, scale: 15, className: 'map_rectangle' },
];
const MapFindRoom = (props) => {
    const [isFlag, setIsFlag] = useState(true);
    const [houseList, setHouseList] = useState([]);//存放房源数据的
    useEffect(() => {
        renderMap()
    }, [])
    useEffect(() => {
        return () => {
            centralPoint = "";
            zoomDataIndex = 0;
        }
    }, [])
    const renderMap = () => {
        map = new BMap.Map("container");//初始化地图
        map.addEventListener("dragstart", () => {//添加事件
            setIsFlag(true);
        })
        map.addControl(new BMap.NavigationControl());//添加平移缩放控件
        setTimeout(() => {
            map.addControl(new BMap.ScaleControl());  //添加比例尺控件
        }, 3000);
        map.addControl(new BMap.GeolocationControl());//添加定位控件
        map.addControl(new BMap.CopyrightControl());//添加版权控件
        getHousesData();//请求房源数据的函数
    }
    const getHousesData = async () => {
        const { cityName } = props;//获取默认的城市
        centralPoint += cityName;//拼接
        Toast.loading('加载中,请稍候...', 2);
        const { value } = await axios({ url: "/area/info", params: { name: cityName } });//请求对应城市的信息
        const result = await axios({ url: `/area/map?id=${value}` });//查询房源数据

        mapCover(result)//给渲染覆盖物的函数传递参数
    }
    const mapCover = (arr) => {
        map.clearOverlays();//清除覆盖物
        map.centerAndZoom(centralPoint, zoomData[zoomDataIndex].scale);//地图的中心点
        // console.log(centralPoint, zoomData[zoomDataIndex].scale);
        arr.forEach(item => {
            const { label: areaName, value, coord, count } = item;//把数据解构
            const obj = {
                position: new BMap.Point(coord.longitude, coord.latitude),
                offset: new BMap.Size(-30, -30)
            }

            //创建覆盖物
            const label = new BMap.Label(`<div class='${zoomData[zoomDataIndex].scale == 15 ? styles.map_rectangle : styles.map_round}'><span>${areaName}</span><span>${count}套</span></div>`, obj);
            label.setStyle({ border: "none", backgroundColor: "transparent" });//清除覆盖物的原样式
            map.addOverlay(label);//在地图上添加覆盖物
            label.addEventListener("click", (e) => {//添加点击事件
                if (zoomDataIndex < 2) {
                    centralPoint += areaName;
                    zoomDataIndex += 1;
                    Toast.loading("加载中,请稍候...")
                    axios({ url: `/area/map?id=${value}` }).then(result => {//查询房源数据
                        mapCover(result);//递归调用
                    })
                } else {
                    Toast.loading('加载中,请稍候...', 1);
                    getThreeHouseList(value);//当缩放级别为15时,调用的函数
                    setIsFlag(false);//
                    const { clientX, clientY } = e.changedTouches[0];
                    const x = window.screen.width / 2 - clientX;
                    const y = window.screen.height / 2 / 2 - clientY;
                    map.panBy(x, y);
                    label.setZIndex(++zoomZIndex);
                }
            })
        })
    }
    const getThreeHouseList = async (id) => {//当缩放级别为15时,请求对应的房源数据
        const { list } = await axios({ url: `/houses?area=${id}` });
        setHouseList(list);
    };
    return <div className="map">
        {/* 头部导航 */}
        <NavBar
            mode="light"
            icon={<Icon type="left" />}
            onLeftClick={() => props.history.go(-1)}>
            地图找房
        </NavBar>
        {/* 地图 */}
        <div className={styles.map_findroom} id="container">
        </div>
        <div className={[styles.house_info, isFlag ? '' : 'show'].join(' ')}>
            <div className={styles.house_title}>
                <h4>房屋列表</h4>
                <p>更多房源</p>
            </div>
            <div className={styles.house_content}>
                {
                    houseList.map(item => <FindRoomItem key={item.houseCode} {...item}></FindRoomItem>)
                }
            </div>
        </div>
    </div>
}
const mapStateToProps = (state) => {
    return { ...state.cityList }
}
export default connect(mapStateToProps)(MapFindRoom)